/*
 * @Author: haungyan
 * @Date: 2020-11-22 21:37:52
 * @LastEditors: haungyan
 * @LastEditTime: 2020-11-24 23:40:36
 * @Description: file content
 * @FilePath: \mini-vue\js\oberver.js
 */
class Observer {
    constructor(data) {
        this.walk(data)
    }

    walk(data) {
        if (!data || typeof data !== 'object') {
            return
        }

        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key])
        })
    }

    defineReactive(obj, key, val) {
        const _this = this
        const dep = new Dep() // 收集依赖
        this.walk(val)

        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: true,
            get() {
                Dep.target && dep.addSub(Dep.target)
                return val
            },
            set(newValue) {
                if (newValue === val) {
                    return
                }
                val = newValue
                _this.walk(val)
                // 发送通知
                dep.notify()
            }
        })
    }
}